package com.cskaoyan.mall.search.mq;

import com.cskaoyan.mall.mq.constant.MqTopicConst;
import com.cskaoyan.mall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class OffSaleMessageConsumer {
    @Value("${rocketmq.namesrv.addr}")
    String namesrvAddr;

    @Value("${rocketmq.producer.group}")
    String producerGroup;
    @Autowired
    SearchService searchService;

    @PostConstruct
    public void offSaleMessageConsumer() throws MQClientException {
        //这边再手写一遍吧，加深记忆
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer(producerGroup);
        defaultMQPushConsumer.setNamesrvAddr(namesrvAddr);
        defaultMQPushConsumer.subscribe(MqTopicConst.PRODUCT_OFFSALE_TOPIC,"*");

        defaultMQPushConsumer.registerMessageListener((MessageListenerConcurrently) (mesList,context)->{
            try {
                log.info("接收到下架信息");
                MessageExt messageExt = mesList.get(0);
                byte[] body = messageExt.getBody();
                String skuIdStr = new String(body, StandardCharsets.UTF_8);
                Long skuId = Long.valueOf(skuIdStr);
                searchService.lowerGoods(skuId);
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }catch (Exception e){
                log.error(e.getMessage());
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });
        defaultMQPushConsumer.start();
    }
}
